import java.awt.Dimension;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.net.*;

import javax.swing.JFrame;

public class Server {

	static ServerSocket serverSocket;
	static Socket socket;
	static DataOutputStream out;
	private static int portNumber = 7777;
	public static GUI gui;
	
	
	public static void main(String[] args) throws IOException
	{
		JFrame frame = new JFrame();
		gui = new GUI();
		frame.getContentPane().add(gui);
		frame.addWindowListener( new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        } );
		frame.setVisible(true);
		frame.setPreferredSize(new Dimension(500,500));
		frame.pack();
		Game manager = new Game();
		boolean continuing = true;
		display("Starting Server...");
		try{
		serverSocket = new ServerSocket(portNumber);
		}
		catch(Exception e)
		{
			gui.display("ERROR: the port 7777 is already in use");
			continuing = false;
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			System.exit(0);
		}
		if(continuing)
		{
			display("Server Started...");
			Thread thread = new Thread(manager);
			thread.start();
			while(true)
			{
				socket = serverSocket.accept();
				display("Connection from: " + socket.getInetAddress());
				out = new DataOutputStream(socket.getOutputStream());
				DataInputStream in = new DataInputStream(socket.getInputStream());
				manager.addUser(socket);
			}
		}
	}

	private static void display(String str)
	{
		gui.display(str);
	}
}
